<template>
  <div class="table-box">
    <ProTable ref="proTable" :tool-button="false" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <!-- <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
      </template> -->

      <template #orgId="scope">
        <span>{{ orgRender(scope, orgList) }}</span>
      </template>
      <template #endTime="scope">
        <span v-if="scope.row.endTime">{{ timeRender(scope) }}</span>
        <el-button v-else type="primary" link @click="onEndRushjob(scope.row)"> 结束突击 </el-button>
      </template>
      <template #workTime="scope">
        <el-button v-if="scope.row.workTime" type="primary" link @click="onCalcWorkTime(scope.row)">{{
          scope.row.workTime
        }}</el-button>
        <el-button v-if="!scope.row.workTime && scope.row.endTime" type="primary" link @click="onCalcWorkTime(scope.row)">
          重新计算
        </el-button>
        <span v-if="!scope.row.workTime && !scope.row.endTime">未结束突击</span>
      </template>
      <template #state="scope">
        <span v-if="scope.row.state === '1'" type="primary">已审核</span>
        <span v-else-if="scope.row.state === '2'" type="primary">不通过</span>
        <el-button v-else type="primary" link @click="approvalRushjob(scope.row)"> 待审核 </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑 </el-button>
        <el-button v-if="scope.row.state === '0'" type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">
          删除
        </el-button>
      </template>
    </ProTable>
    <EditDrawer ref="drawerRef" />
    <InfoDialog ref="infoRef"></InfoDialog>
    <ImportExcel ref="dialogRef" />
    <ApprovalDialog title="突击审核" ref="approvalDrawer" @change="onApprovalSave" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, computed, onMounted } from "vue";
import { RushJob } from "@/api/types/base";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import EditDrawer from "./editDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { EditPen, View, Delete } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { orgRender, timeRender } from "@/hooks/useColumnRender";
import { useUserStore } from "@/stores/modules/user";
import InfoDialog from "@/layouts/components/Header/components/InfoDialog.vue";
import { useDataStore } from "@/stores/modules/data";
import { Md5 } from "ts-md5";
import { RenderScope } from "@/components/ProTable/interface";
import ApprovalDialog from "@/components/SelectFilter/approval-dialog.vue";
import { ElMessage } from "element-plus";
import { calculateOvertimeHours } from "@/utils";

const initVar = reactive({
  tbName: "rushJobs",
  tbCnName: "突击"
});

const defaultDate = ref<Date>(new Date());
const defaultOrgId = ref();

// ProTable 实例
const proTable = ref<ProTableInstance>();
const userUser = useUserStore();
const dataStore = useDataStore();

const initParam = reactive({
  condition: { charge_user: userUser.userInfo._id },
  options: { sort: { startTime: -1 } }
});

const getTableList = async (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  if (newParams.condition && newParams.condition.startTime) {
    let curDate = new Date(newParams.condition.startTime);
    let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
    let startDate = new Date(year, month, 1);
    let endDate = new Date(year, month + 1, 0, 23, 59, 59);
    newParams.condition.startTime = { $gte: startDate, $lte: endDate };
  }
  return apiService.findPage(initVar.tbName, newParams.condition, newParams.options);
};

const approvalDrawer = ref<InstanceType<typeof ApprovalDialog> | null>(null);
const approvalRushjob = (data: any) => {
  approvalDrawer.value?.openDialog(data);
};

const paramKey = ref();
const orgSelectList = computed(() => dataStore.getCommonDataByName(paramKey.value));
const orgList = computed(() => dataStore.orgList);
onMounted(async () => {
  let params = {
    condition: {
      $or: [{ leader: userUser.userInfo._id }, { superVisor: userUser.userInfo._id }],
      leaf: "1"
    },
    options: { sort: { sort: 1 } }
  };
  paramKey.value = Md5.hashStr(JSON.stringify(params));
  let data = await dataStore.findList(paramKey.value, () => apiService.find("orgs", params.condition, params.options));
  if (data && data.length > 0) {
    defaultOrgId.value = data[0]._id;
    if (columns[3].search) {
      columns[3].search["defaultValue"] = defaultOrgId.value;
      proTable.value?.setInitSearch();
      proTable.value?.search();
    }
  }

  dataStore.findOrgList();
});

const changeDayRender: any = (scope: RenderScope<RushJob>) => {
  if (Number(scope.row["workTime"]) >= 6 && scope.row["isHoliday"] === "1") {
    return 0.5;
  } else {
    return "--";
  }
};

// 表格配置项
const columns = reactive<ColumnProps<RushJob>[]>([
  { type: "index", label: "序号", width: 85 },
  { prop: "userName", label: "姓名", width: 100, search: { el: "input", like: true, order: 3 } },
  { prop: "workNo", label: "工号", width: 100 },
  {
    prop: "orgId",
    label: "组织",
    width: 160,
    fieldNames: { label: "name", value: "_id" },
    // search: { el: "select", props: { filterable: true }, order: 2 },
    enum: orgSelectList
  },
  { prop: "workNote", label: "突击内容", align: "left" },
  {
    prop: "startTime",
    label: "开始时间",
    width: 150,
    render: timeRender,
    search: { el: "date-picker", props: { type: "month" }, order: 1, defaultValue: defaultDate, label: "月份" }
  },
  {
    prop: "endTime",
    label: "结束时间",
    width: 150
  },
  { prop: "workTime", label: "突击时间(小时)", width: 140 },
  {
    prop: "isHoliday",
    label: "节假日",
    width: 100,
    search: { el: "select", props: { filterable: true } },
    enum: () => apiService.findClassify("IS_NOT"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "changeDay", label: "调休(天)", width: 100, render: changeDayRender },
  {
    prop: "state",
    label: "状态",
    width: 100,
    search: { el: "select", props: { filterable: true } },
    enum: () => apiService.findClassify("APPROVAL_STATE"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "operation", label: "操作", align: "left", fixed: "right", width: 240 }
]);

// const getExcelConfig = (): ExportObj => {
//   let newParams = JSON.parse(JSON.stringify(proTable.value?.searchParam));
//   if (newParams.startTime) {
//     let curDate = new Date(newParams.startTime);
//     let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
//     let startDate = new Date(year, month, 1);
//     let endDate = new Date(year, month + 1, 0, 23, 59, 59);
//     newParams.startTime = { $gte: startDate, $lte: endDate };
//   }
//   return {
//     condition: newParams,
//     tableName: initVar.tbName,
//     keyPropName: "_id",
//     enumTypes: ["APPROVAL_STATE", "IS_NOT"],
//     tableConfigs: [{ tableName: "orgs", fields: ["_id", "name"] }],
//     header: [
//       { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
//       {
//         header: "姓名",
//         width: 8,
//         ext: { prop: "userName", type: ExportColType.DEFAULT }
//       },
//       { header: "工号", width: 10, ext: { prop: "workNo", type: ExportColType.DEFAULT } },
//       { header: "组织", width: 15, ext: { prop: "orgId", type: ExportColType.TABLE, key: "orgs" } },
//       { header: "突击内容", width: 50, ext: { prop: "workNote", type: ExportColType.DEFAULT } },
//       {
//         header: "开始时间",
//         width: 16,
//         ext: { prop: "startTime", type: ExportColType.DATE_TIME }
//       },
//       {
//         header: "结束时间",
//         width: 16,
//         ext: { prop: "endTime", type: ExportColType.DATE_TIME }
//       },
//       {
//         header: "突击时间",
//         width: 8,
//         ext: { prop: "workTime", type: ExportColType.DEFAULT }
//       },
//       {
//         header: "节假日",
//         width: 8,
//         ext: { prop: "isHoliday", type: ExportColType.ENUM, key: "IS_NOT" }
//       },
//       { header: "状态", width: 10, ext: { prop: "state", type: ExportColType.ENUM, key: "APPROVAL_STATE" } }
//     ]
//   };
// };

// 导出数据
// const downloadFile = async () => {
//   ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
//     useDownload(apiService.commonExport, `突击清单-${useDateFormat(new Date(), "YYYY-MM-DD").value}`, "", getExcelConfig(), false)
//   );
// };

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof EditDrawer> | null>(null);
const infoRef = ref<InstanceType<typeof InfoDialog> | null>(null);
const openDrawer = (title: string, row: Partial<RushJob> = {}) => {
  if (userUser.userInfo.workNo) {
    const params = {
      title,
      tbName: initVar.tbName,
      isView: title === "查看",
      row: row,
      api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
      getTableList: proTable.value?.getTableList
    };
    drawerRef.value?.acceptParams(params);
  } else {
    infoRef.value?.openDialog();
  }
};

const onEndRushjob = async row => {
  let curDate = new Date();
  let workTime = calculateOvertimeHours(row.startTime, row.endTime);
  row.endTime = curDate;
  row.workTime = workTime;
  useHandleData(apiService.updateById, initVar.tbName, { _id: row._id, endTime: curDate, workTime: workTime }, "结束突击").catch(
    () => {
      delete row.endTime;
      delete row.workTime;
    }
  );
};

const onCalcWorkTime = async row => {
  if (row.startTime && row.endTime) {
    let workTime = calculateOvertimeHours(row.startTime, row.endTime);
    await useHandleData(apiService.updateById, initVar.tbName, { _id: row._id, workTime: workTime }, "重新计算突击时间");
    row.workTime = workTime;
  }
};

const onApprovalSave = async row => {
  if (row.state && row.approvalReason) {
    await apiService.updateById(initVar.tbName, row);
    proTable.value?.tableData.forEach(item => {
      if (item._id === row._id) {
        item.state = row.state;
      }
    });
    ElMessage.success("审核完成");
  }
};

// 删除信息
const deleteAccount = async (params: RushJob) => {
  await useHandleData(apiService.deleteById, initVar.tbName, params._id, `删除`);
  proTable.value?.getTableList();
};
</script>
